package com.zxy.employee.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.employee.entity.EmployeeEntity;
import com.zxy.employee.entity.EmployeeSchoolEntity;
import com.zxy.employee.mapper.EmployeeSchoolMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class EmployeeSchoolService extends ServiceImpl<EmployeeSchoolMapper, EmployeeSchoolEntity> {

    @Autowired
    private EmployeeSchoolMapper employeeSchoolMapper;

    public List<EmployeeSchoolEntity> selectEmployeeSchoolByEmployeeId(Integer employeeId) {
        List<EmployeeSchoolEntity> employeeEntities = employeeSchoolMapper.selectList(new QueryWrapper<EmployeeSchoolEntity>()
        .lambda().eq(EmployeeSchoolEntity::getEmployeeId,employeeId));
        return employeeEntities;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<EmployeeSchoolEntity> save(Integer employeeId,List<EmployeeSchoolEntity> employeeSchools) {

        List<EmployeeSchoolEntity> employeeSchoolEntities = this.selectEmployeeSchoolByEmployeeId(employeeId);

        if(Objects.isNull(employeeSchools)) {
            employeeSchools = new ArrayList<>();
        }
        List<Integer> schoolIds = employeeSchools.stream().map(e -> e.getEmployeeSchoolId()).collect(Collectors.toList());

        for(EmployeeSchoolEntity e: employeeSchoolEntities) {
            if(!schoolIds.contains(e.getEmployeeSchoolId())) {
                employeeSchoolMapper.deleteById(e.getEmployeeSchoolId());
            }
        }

        this.saveOrUpdateBatch(employeeSchools);

        return this.selectEmployeeSchoolByEmployeeId(employeeId);
    }
}
